﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using OnlineMealOrdering.Persistence;

namespace OnlineMealOrdering
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            log4net.Config.XmlConfigurator.Configure();

            Database.SetInitializer(new OnlineStoreDbInitializer());

            //RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
            

        }

        protected void Application_Error(object sender, EventArgs e)
        {
            //get last exception
            var exception = Server.GetLastError();
            var httpException = new HttpException(null, exception);

            OnlineMealOrdering.Common.WebLog<MvcApplication>.AddLog("网站出现错误信息如下:", httpException);

            var routeData = new RouteData();
            routeData.Values.Add("controller", "Exception");
            routeData.Values.Add("action", "ShowGlobalException");
            routeData.Values.Add("httpException", httpException);
            Server.ClearError();

            //generate action for exception
            RequestContext requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);
            var errorController = ControllerBuilder.Current.GetControllerFactory().CreateController(requestContext, "Exception");

            //execute action to show exception
            errorController.Execute(requestContext);
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            
        }

    }
}